import { getStorageSync, removeStorageSync, setStorageSync } from '@tarojs/taro';
import { getGlobalData } from './globalData';
import { wxData, CacheUserInfo } from '../constant/cache';
import { proxy } from '../constant/config';

/**
 * 取缓存
 * @param {*} key
 * @param {*} isDelete
 */
export const getCache = (key, isDelete = false) => {
  const a = getStorageSync(key);
  if (isDelete) {
    removeStorageSync(key);
  }
  return a;
};

/**
 * 设置缓存
 * @param {*} key
 * @param {*} value
 */
export const setCache = (key, value) => {
  setStorageSync(key, value);
};

/**
 * 清除缓存
 * @param {*} key
 */
export const removeCache = (key) => {
  removeStorageSync(key);
};

export const getUserInfo = () => {
  return getGlobalData(wxData.userInfo) || getStorageSync(CacheUserInfo) || {};
};

/**
 * 数组转对象
 * @param {*} rs 集合
 * @param {*} key 需要转换目标key的名称
 */
export const arrayToObject = (rs = [], key, render = null) => {
  let o = {};
  rs.forEach((x) => {
    o[x[key]] = render ? render(x) : x;
  });
  return o;
};

export const formatHtml = (str) => {
  return str
    .replace(
      /src="\/biz\/www\//gi,
      ' style="max-width:100%;height:auto;display:block;" src="' + proxy + '/'
    )
    .replace(
      /src="data\/upload\//gi,
      ' style="max-width:100%;height:auto;display:block;" src="' +
        proxy +
        '/data/upload/'
    );
};

export const formatFile = (str) => {
  return proxy + str;
};
